/**
 * 运营：商品评价列表页
 */
import React, { Component, PropTypes } from 'react';
import { Relax } from 'iflux2'
import { Map, OrderedSet } from 'immutable';
import { Link } from 'react-router'
import { Table, Row, Col, Button, Spin, Modal, message, Popover } from 'antd';
import moment from 'moment'
import { listQL } from '../ql';
import { orderColumns } from '../constant/columns';
import CommentDetail from '../component/comment-detail';
import OrderTable from 'components/OrderTable'
import noop from 'util/noop';

@Relax
class CommentList extends Component {
    
    static defaultProps = {
        list: listQL,
        pagination: Map(),
        condition: Map(),
        loading: true,
        setCommentDetail: noop,
        deleteComments: noop,
        updateCommentShowState: noop,
        queryOrderList:noop,
        setPagination:noop,
    }

    constructor(props) {
        super(props);

        //页面滚动控制，翻页时调用
        this.pageWrapper = null;
        this.state = {
            selectedRowKeys: [],
            filterName: '所有商品评价',
            filters: [],
            openList:[],//弹开的tid列表
            // 控制评论的显示状态
            commentVisible: false

        }
    }
    componentWillReceiveProps(nextProps) {
        if (this.props.pagination.get('pageNum') !== nextProps.pagination.get('pageNum')) {
            this.setState({
                selectedRowKeys: []
            })
        }
    }

    componentDidMount() {
       
        if(window.document.getElementById("react-content")){
            this.pageWrapper = window.document.getElementById("react-content").getElementsByClassName("page-wrapper")[0];
        }
    }
    
    scrollTop(){
        if(this.pageWrapper){
            this.pageWrapper.scrollTop = 0;
        }else if(window.document.getElementById("react-content")){
            window.document.getElementById("react-content").getElementsByClassName("page-wrapper")[0].scrollTop = 0;
        }
    }

    render() {
        const { list, loading, pagination } = this.props;
        const { selectedRowKeys } = this.state;

        const rowSelection = {
            selectedRowKeys: selectedRowKeys,
            onSelectAll: (selected, selectedRows, changeRows) => this.selectAll(selected, selectedRows, changeRows),
            getCheckboxProps: record => ({
                // 如果一笔订单下的所有商品单都没有评价，禁止这笔订单被选中
                disabled: !this.hasComment(record)
            })
        };

         const orderHeader = (<Table pagination={false}
                rowSelection={rowSelection}
                columns={this.renderHeaderColumns()}
                dataSource={list.toJS()}
             />);

        let self = this;
        // 以下三个字段均用来控制pages中的checkbox的状态
        // 全选按钮是否可用：至少存在一条有评价的订单
        //let pageSelectDisabled = !list.some(order => self.hasComment(order))
        // 全选标识状态：当前页所有有评价的订单都已被选中。需要对selectedRowKeys.length做判断，否则如果当前页所有订单都没有评价时会返回true
        //let selectAll = selectedRowKeys.length !== 0 && list.filterNot(order => !self.hasComment(order) || OrderedSet(selectedRowKeys).has(order.get('tid'))).isEmpty();
        // 是否处于中间状态：全选状态为false且已经有订单被选中
        //let indeterminate = !selectAll && !list.filter(order => OrderedSet(selectedRowKeys).has(order.get('tid'))).isEmpty();
        
        const listRowSelection = {
            selectedRowKeys: selectedRowKeys,
            onChange:this.handleSelect,
            getCheckboxProps:record=>{
                return {
                    disabled:!record.itemOrders.some(itemOrder => typeof itemOrder.comment !== 'undefined')
                }
            }
        }
        const page = {
            current:pagination.get('pageNum'),
            total:pagination.get('totalCount'),
            pageSize:pagination.get('pageSize'),
            onChange:this.changePageNum,
            onShowSizeChange:this.changePageSize,
            showTotal:(total)=>`共${total}条`,
            showQuickJumper: true,
            showSizeChanger: true,
        }
        return (
            <div>
                {this.renderToolBar()}
                <OrderTable
                    loading={loading}
                    rowKey='tid'
                    hideKey="itemOrders"
                    rowSelection={listRowSelection}
                    header={orderHeader}
                    rowHeader={this.renderRowHeader}
                    dataSource={list.toJS()}
                    columns={this.renderSubColumns()}
                    pagination={page}
                />

                 <Modal title="评价详情" visible={this.state.commentVisible} footer={false} onCancel={this.handleCancel}
                    width="580px">
                    <CommentDetail />
                </Modal>
            </div>
        );
    }

     /**
     * 全选操作
     * @param selected
     * @param selectedRows
     * @param changeRows
     */
    selectAll(selected, selectedRows, changeRows) {
        let selectedRowKeys = [];
        let self = this;
        selected && selectedRows.forEach(row => {
            // 只有有评价的订单才能被选中
            if (self.hasComment(row) && selectedRowKeys.indexOf(row.tid) < 0) {
                selectedRowKeys.push(row.tid)
            }
        });
        this.setState({ selectedRowKeys });
    }
    handleSelect = (selectedRowKeys,selectedRows) => {
        this.setState({
            selectedRowKeys
        })
    }
    /**
     * 判断这笔订单是否有评价
     * @param {*} order 
     */
    hasComment(order) {
        let simpleOrder = order;
        if (typeof order.toJS === 'function') {
            simpleOrder = order.toJS();
        }
        return simpleOrder.itemOrders.some(itemOrder => typeof itemOrder.comment !== 'undefined')
    }
    renderHeaderColumns(){
        return orderColumns.concat([
            {
                title: '买家评价内容',
                width: 250,
                key: 'comment',
                className: "ant-table-th-right pr8 va-t"
            },
            {
                title: '所有订单',
                width: 385,
                key: 'operation',
                className: "ant-table-th-right pr8 va-t"
            },
        ])
    }
    renderToolBar(){
        let disabled = this.props.list.filter(order => this.hasComment(order)).isEmpty();
        return (
            <Row className="table-toolbar">
                <Col span={12}>
                    <Button type="ghost" disabled={disabled} onClick={this.handleDeleteComments}>批量删除</Button>
                </Col>
            </Row>
        );
    }

    renderRowHeader = (record) =>{
        let consigneeName = record['consigneeInfo']['consigneeName'] || ''
        return (
            <Row>
                <Col span={18}>
                    <div className="order-info">
                        <p>
                            <span className="mr10">{`买家：${record.buyNickName}`}</span>
                            {consigneeName === '' ? null : <span className="mr10 t-grayer">{`收货人：${consigneeName}`}</span>}
                            {consigneeName === '' ? null : <span className="mr10 t-grayer">{record['consigneeInfo']['consigneeMobile']
                                || record['consigneeInfo']['consigneePhone']}</span>}
                        </p>
                        <p>
                            <span className="mr10">{`订单号：${record.tid}`}</span>
                            <span className="mr10 t-grayer">{record.payTypeName}</span>
                            <span className="mr10 t-grayer">{`配送方式：${record.shipMethodName}`}</span>
                            <span className="mr10 t-grayer">{`下单时间：${moment(record.ctime).format('YYYY/MM/DD HH:mm:ss')}`}</span>
                        </p>
                    </div>
                </Col>
                <Col span={6}>
                    <div className="t-right">

                    </div>
                </Col>
            </Row>
        )
    }
    /**
     * 这段代码未测试
     * TODO:待测试显示相应的商品列表和评价列表
     */
    renderSubColumns = () => {
        const { list } = this.props;
        const { openList } = this.state
        let _orderColumns = orderColumns.slice(0);
        /**
         * 重新覆盖此函数，因为要读取父组件的open状态和商品数
         * 根据open状态显示剩余的商品
         */
        _orderColumns[0].render = (value, record, index) => {

            return {
                children: <GoodsList open={openList.indexOf(record.tid) !== -1} more={list.get(0).get('itemOrders').count() > 1} itemOrders={value} toggleMore={this.showMore} />,
                props: {
                    colSpan: 2
                }
            }
        }
        return _orderColumns.concat(
            {
                title: '',
                width: 120,
                className: "ant-table-th-center va-t",
                dataIndex: 'totalTradeCash',
                render: (value, record, index) => {
                return (
                    <div className="real-pay">
                    <p className="total-price">&yen;{(value || 0).toFixed(2)}</p>
                    <p className="freight">（含运费：&yen;{(record.logisticsFee || 0).toFixed(2)}）</p>
                    <p className="goods-num">
                        共
                        {list.get(index).get('itemOrders').reduce(((sum, item) => sum + item.get('itemNumber')), 0)}
                        件
                    </p>
                    </div>
                )
                }
            },
            {
                title: "买家评价内容",
                width: 250,
                className: "ant-table-th-center  va-t",
                render: (v, record, index) => {
                    let open = openList.indexOf(record.tid) !== -1;
                    let itemOrders = open ? record.itemOrders : record.itemOrders.slice(0,1);
                    return <div>
                        {itemOrders.map((itemOrder, index) => {
                            let rtDom = [<div className="evaluate-item" key={index}>
                                {itemOrder.comment ? <span href="javascript:;" onClick={e => this.showCommentDialog(itemOrder.oid)}>
                                    <span className="t-pointer evaluate-content">{itemOrder.comment.content}</span>
                                </span> : <span className="t-grayer">客户还没有评价</span>}
                                {itemOrder.commentSun ? <Icon type="camera-o" className="t-primary font-20 t-pointer" onClick={e => this.showCommentDialog(itemOrder.oid)} /> : null}
                            </div>];
                            if (index == 0) {
                                return rtDom;
                            } else {
                                return [<div className="split-line" />, rtDom]
                            }
                        })}
                    </div>
                }
            }, 
            {
                title: '操作',
                width: 270,
                key: 'orderOpt',
                className: "ant-table-th-right pr8 va-t",
                render: (value, record, index) => {
                    let open = openList.indexOf(record.tid) !== -1;
                    let itemOrders = open ? record.itemOrders : record.itemOrders.slice(0,1);
                    return record.itemOrders.map((itemOrder, index) => {
                        const { comment, replies } = itemOrder;

                        let rtDom = !comment ? <div className="evaluate-item"></div> : [<div className="evaluate-item">
                            <div className="t-left evaluate-reply">
                                {replies ? replies[replies.length - 1].content : <span className="t-grayer">您还未回复</span>}
                            </div>
                            <div className="button-list">
                                <Popover trigger="hover" placement="bottom" content={<ul>{this.renderOpts(itemOrder)}</ul>}>
                                    <Button type="ghost" icon="ellipsis" />
                                </Popover>
                                <Button type="primary" className="pushl" onClick={e => this.showCommentDialog(itemOrder.oid)}>回复</Button>
                            </div>
                        </div>];
                        if (index == 0) {
                            return rtDom;
                        } else {
                            return [<div className="split-line" />, rtDom]
                        }
                    })
                }
            }
        )
    }
    /**
     * 需要goods-list组件配合改回调函数
     */
    showMore = (open, tid) => {
        const { openList } = this.state;
        if(open){
            openList.push(tid);
        }else{
            openList = openList.filter(tid => tid != tid);
        }
        this.setState({
            openList
        })
    }
    /**
     * 对评价的操作
     * @returns {[XML,XML]}
     */
    renderOpts = (itemOrder) => {
        return [
            <li><Button type="ghost" onClick={e => this.updateCommentShowState(itemOrder.comment)}>{itemOrder.comment.showState === 1 ? '前台隐藏' : '前台显示'}</Button></li>,
            <li><Button type="ghost mt8" onClick={(e) => this.deleteComment(itemOrder.oid)}>删除评价</Button></li>,
        ]
    }
    changePageNum = (pageNum, pageSize) => {
        this.props.setPagination({pageNum})
        this.queryOrderList();
        this.scrollTop();
    }

    changePageSize = (current, pageSize) => {
        this.props.setPagination({pageNum:1,pageSize})
        this.queryOrderList();
        this.scrollTop();
    }
    queryOrderList = () =>{
        //const { condition } = this.props;
        this.props.queryOrderList();
    }
    showCommentDialog = (oid) => {
        this.props.setCommentDetail(oid);
        this.setState({
            commentVisible: true
        });
    }

    handleCancel = (e) => {
        this.setState({
            commentVisible: false
        });
    }

    /**
     * 批量删除评价
     */
    handleDeleteComments = (e) => {
        e.preventDefault();
        // 根据选中的订单编号列表tids获取对应的商品单编号列表oids
        let tids = this.state.selectedRowKeys;
        if (tids.length === 0) {
            message.warning('请先选择要删除的评价', 2);
            return;
        }
        let oids = [];
        this.props.list.forEach(order => {
            if (tids.indexOf(order.get('tid')) < 0) {
                return;
            }
            order.get('itemOrders').forEach(itemOrder => {
                // 某个商品单的评价可能被单独删掉了，需要过滤掉
                if (!!itemOrder.get('comment')) {
                    oids.push(itemOrder.get('oid'))
                }
            })
        })
        // 删除评价
        Modal.confirm({
            content: '确定删除吗?',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                this.deleteComments(oids);
                // 批量删除时需要重置复选框选中状态
                this.setState({
                    selectedRowKeys: []
                });
            },
        });
    }
    deleteComment = (oid) => {
        this.deleteComments([oid])
    }
    deleteComments = (oids) => {
         this.props.deleteComments({ oids })
    }

    updateCommentShowState = (comment) => {
        this.props.updateCommentShowState({
            'oid': comment.billId,
            'commentId': comment.id,
            'showState': comment.showState === 1 ? 0 : 1
        })
    }
}


export default CommentList;